package j20;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * @author chengshuai
 * @date 2021/4/9 21:48
 */
public class ContainerNotSafeDemo1 {


    static List<String> list = new ArrayList<>();

    static {
        list.add("a");
        list.add("b");
        list.add("c");
    }


    public static void main(String[] args) {

    }

    /**
     * 普通遍历添加
     */
    @Test
    public void f1() {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
            if (i == 2) {
                list.add("d");
            }
        }
    }

    /**
     * 普通遍历删除
     */
    @Test
    public void f2() {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
            if (i == 1) {
                list.remove(list.get(i));
            }
        }
    }

    /**
     * foreach 遍历添加
     */
    @Test
    public void f3() {
        for (String s:list) {
            System.out.println(s);
            list.add("d");
        }
    }

    @Test
    public void f4() {
        Iterator<String> lit = list.iterator();
        while (lit.hasNext()) {
            if (lit.next().equals("c")) {
                list.add("d");
            }
        }
    }

    @Test
    public void f5() {
        ListIterator<String> lit = list.listIterator();
        while (lit.hasNext()) {
            String s = lit.next();
            if (s.equals("b")) {
                lit.add("d");
            }
            System.out.println(s);
        }
        System.out.println(list);
    }


}
